package com.xiaoy.core.base.security.role.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.xiaoy.core.base.menu.entity.Menu;
import com.xiaoy.core.base.security.role.dao.RoleDao;
import com.xiaoy.core.base.security.role.entity.Role;
import com.xiaoy.core.base.util.store.config.ConfigTable;
import com.xiaoy.dao.DaoUtil;

@Service("roleService")
public class RoleService {

	@Resource
	private RoleDao roleDao;
	
	@Resource
	private DaoUtil dao;
	
	public Page<Role>filterPage(Page<Role>page){
		roleDao.findPage(page, page.getFilters());
		return page;
	}
	
	public List<Role> getRoles () {
		return roleDao.getAll();
	}
	
	@Transactional
	public void save(Role role) {
		roleDao.save(role);
	}
	
	/**
	 * 获得roleIds下所有的菜单
	 * @param ids
	 * @return
	 * TODO
	 */
	public List<Menu> findMenuByRoleIds (String ids){
		
		String sql = "select * from "+
				ConfigTable.Security.ROLE_TABLENAME+ " r,"+
				ConfigTable.Menu.MENU_ROLE_TABLENAME + " mr,"+
				ConfigTable.Menu.MENU_TABLENAME +" m,"+
				"where r.id = mr.role_id and mr.menu_id = m.id and r.role_id in(?) ";
		return dao.query(Menu.class,sql, ids);
	}
	
	/**
	 * 获得roleIds下所有的菜单
	 * @param ids
	 * @return
	 * TODO
	 */
	public List<Menu> findMenuByRoleIds (List<Role> roles){
		
		String ids = "";
		for (Role r:roles) {
			ids += r.getId()+",";
		}
		if (ids.length()>0) {
			ids = ids.substring(0, ids.length()-1);
		}
		return  findMenuByRoleIds(ids);
	}
	
}
